﻿using Unity.Entities;
using Unity.Collections;
using UnityEngine;
using Unity.Transforms;
using Unity.Mathematics;
using Unity.Burst;

[DisableAutoCreation]
public partial struct FireSystem : ISystem
{
    public EntityManager _entityManager;
    int frame;
    int cooldown;
    public void OnCreate(ref SystemState state)
    {
        state.RequireForUpdate<PlayerTag>();
        state.RequireForUpdate<InputComp>();
        frame = 10;
        cooldown = 10;
    }
    public void OnUpdate(ref SystemState state)
    {
        _entityManager = state.EntityManager;
        if (frame > 0)
        {
            frame--;
            return;
        }
        //获取玩家单例
        Entity player = SystemAPI.GetSingletonEntity<PlayerTag>();
        //
        var arrowSpawner = SystemAPI.GetSingleton<ArrowSpawner>();
        //获取子节点
        DynamicBuffer<Child> children = SystemAPI.GetBuffer<Child>(player);
        float3 ShootPos = SystemAPI.GetComponent<LocalToWorld>(children[0].Value).Position;

        var inputComp = SystemAPI.GetSingleton<InputComp>();

        EntityCommandBuffer ecb = new EntityCommandBuffer(Allocator.Temp);

        if(cooldown > 0)
        {
            cooldown--;
        }
        else
        {
            cooldown = 3;
        }

        if (inputComp.isShoot && cooldown <= 0)
        {
            inputComp.isShoot = false;
            
            Entity entity = _entityManager.Instantiate(arrowSpawner.preFab);
            ecb.AddComponent(entity, new ArrowTag());
            ecb.AddComponent(entity, new ArrowData() { lifeTime =5});

            LocalTransform transform = _entityManager.GetComponentData<LocalTransform>(entity);

            transform.Position = ShootPos;

            //获得朝向鼠标的方向
            var mousePos = inputComp.MousePos;
            var worldPos = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, 0));
            var dir = new float2(worldPos.x, worldPos.y) - ShootPos.xy;
            var angle = dir.float2Angle2D();
            transform.Rotation = Quaternion.Euler(0, 0, angle);
            ecb.SetComponent(entity, transform);
            ecb.AddComponent(entity, new VelComp() { value = angle.Angle2float2()*5 });

        }
        ecb.Playback(_entityManager);
        ecb.Dispose();
    }


}
